<template>
  <el-dialog
    :title="showTitle"
    :visible.sync="dialogData.isShow"
    :before-close="labelHandleClose"
    width="600px"
  >
    <div class="form-box">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
        <el-form-item label="角色名称" label-width="90px" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="权限字符" label-width="90px" prop="roleKey">
          <el-input v-model="ruleForm.roleKey"></el-input>
        </el-form-item>
        <el-form-item label="显示顺序" label-width="90px" prop="roleSort">
          <el-input v-model.number="ruleForm.roleSort"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="90px">
          <template>
            <el-switch
              v-model="ruleForm.status"
              active-value="0"
              inactive-value="1"
              active-color="#1DC8A4"
            ></el-switch>
          </template>
        </el-form-item>
        <el-form-item label="备注" label-width="90px" prop="msg">
          <el-input v-model="ruleForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限" label-width="90px" class="el-form-tree">
          <el-tree
            ref="tree"
            v-loading="loading"
            :data="data"
            show-checkbox
            node-key="id"
            :highlight-current="true"
            :default-expand-all="isShowList"
            :expand-on-click-node="false"
            :check-strictly="isRelation"
            :props="defaultProps"
          >
            <span slot-scope="{ node, data }">
              <span v-html="data.name"></span>
            </span>
          </el-tree>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="success" plain @click="cancelLabel">
        取 消
      </el-button>
      <el-button
        type="success"
        :loading="loading"
        @click="confirmLabel('ruleForm')"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  editFormData,
  editGetTree,
  addRole,
  editRole,
  roleKey,
  roleName
} from '@/api/system/roles' // 接口
export default {
  name: 'RoleAddEdit',
  msg: '角色管理-新增/编辑弹窗',
  props: ['dialogData'],
  data() {
    var valiPostSort = (rule, value, callback) => {
      if (!value) {
        callback(new Error('显示顺序不能为空'))
      } else {
        if (isNaN(value)) {
          callback(new Error('显示顺序必须为数字值'))
        } else {
          callback()
        }
      }
    }
    // 校验角色权限是否重复
    var valiRoleKey = (rule, value, callback) => {
      let id = this.roleId ? this.roleId : 0
      let obj = {
        type: 'role-code',
        roleKey: this.ruleForm.roleKey,
        roleId: this.roleId
      }
      console.log(obj)
      roleKey(
        id,
        obj,
        (response) => {
          if (response) {
            //true已重复
            callback(new Error('角色权限已使用，请更换'))
          } else {
            //false-无重复
            callback()
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    // 校验角色名称是否重复
    var valiRoleName = (rule, value, callback) => {
      let id = this.roleId ? this.roleId : 0
      let obj = {
        type: 'role-name',
        roleName: this.ruleForm.roleName,
        roleId: this.roleId
      }
      roleName(
        id,
        obj,
        (response) => {
          if (response) {
            //true已重复
            callback(new Error('角色名称已使用，请更换'))
          } else {
            //false-无重复
            callback()
          }
        },
        (res) => {
          callback(new Error('校验失败'))
        }
      )
    }
    return {
      isAdd: true, // 新增-true,编辑-false
      showTitle: '',
      loading: true,
      roleId: '', // 角色编号
      isShowList: false, // 是否全部展开
      isRelation: true, //是否严格的遵循父子不互相关联的做法
      data: [],
      defaultProps: {
        children: 'childs',
        label: 'name'
      },
      // 表单数据
      ruleForm: {
        roleName: '',
        roleKey: '',
        roleSort: null,
        remark: '',
        menuIds: [],
        status: false
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { validator: valiRoleName, trigger: 'blur' }
        ],
        roleKey: [
          { required: true, message: '请输入权限字符', trigger: 'blur' },
          { validator: valiRoleKey, trigger: 'blur' }
        ],
        roleSort: { validator: valiPostSort, trigger: 'blur' }
      }
    }
  },
  mounted() {
    this.isAdd = this.dialogData.type === 'add'
    this.showTitle = this.isAdd ? '新增' : '编辑'
    if (!this.isAdd) {
      // 编辑
      this.roleId = this.dialogData.roleId
      this.getFormData()
    }
    this.getDataList()
  },
  methods: {
    /* 编辑时获取表单详情 */
    async getFormData() {
      await editFormData(this.roleId, (response) => {
        this.ruleForm = { ...response }
      })
    },
    /* 获取部门信息树状结构 */
    async getDataList() {
      this.loading = true
      let obj = {}
      if (!this.isAdd) {
        obj = {
          roleId: this.roleId
        }
      }
      await editGetTree(obj, (response) => {
        this.loading = false
        this.data = response.ztrees
        this.$refs.tree.setCheckedKeys(response.menus)
        this.isRelation = false
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.roleId = null
      this.dialogData.roleId = null
      this.dialogData.isShow = false
    },
    /* 确认提交 */
    confirmLabel(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let checkAry = this.$refs.tree.getCheckedKeys()
          let halfAry = this.$refs.tree.getHalfCheckedKeys()
          this.ruleForm.menuIds = [...checkAry, ...halfAry]
          _this.subForm()
        } else {
          return false
        }
      })
    },
    /* 提交表单 */
    async subForm() {
      this.loading = true
      let obj = { ...this.ruleForm }
      if (this.isAdd) {
        // 新增
        await addRole(
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message({
              message: this.showTitle + '失败',
              type: 'warning'
            })
          }
        )
      } else {
        editRole(
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            this.loading = false
            this.$message({
              message: this.showTitle + '失败',
              type: 'warning'
            })
          }
        )
      }
    }
  }
}
</script>
<style lang="less">
.el-dialog {
  border-radius: 4px;

  .el-dialog__header {
    border-bottom: 1px solid rgba(225, 228, 233, 1);
  }
}
.el-form-tree {
  min-height: 310px !important;
  max-height: 300px;
  overflow: auto;
}
</style>
